package solution1.demo_s;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpServer {

    private ServerSocket serverSocket;
    private ExecutorService pool;

    public TcpServer(int port) throws IOException {
        this.serverSocket = new ServerSocket(port);
        this.pool = Executors.newCachedThreadPool();
    }

    public void start() throws IOException {
        System.out.println("[TcpServer] 启动");
        //1.接收客户端连接
        Socket clientSocket = serverSocket.accept();
        pool.submit(() -> {
            processClient(clientSocket);
        });
    }

    private void processClient(Socket clientSocket) {
        System.out.println("[TcpServer] 客户端上线！ ip: " + clientSocket.getInetAddress() +
                ", port: " + clientSocket.getPort());
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while(true) {
                //1.读取请求
                String request = scanner.next();
                //2.根据请求计算响应
                String response = process(request);
                //3.返回响应
                printWriter.println(response);
                printWriter.flush();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String process(String request) {
        return request;
    }

}

class Main {
    public static void main(String[] args) throws IOException {
        TcpServer tcpServer = new TcpServer(9090);
//        tcpServer.start();
        HashMap<TcpServer, TcpServer> map = new HashMap<>();
        TcpServer tcpServer1 = map.get(null);
        System.out.println(tcpServer1);
    }
}
